package com.gismore.jsonp.core;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import lombok.extern.log4j.Log4j2;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.util.List;

import static com.gismore.jsonp.common.util.ClassPathUtils.classPath;
import static java.util.stream.Collectors.toList;

/**
 * Description: 通过base64.js 将ftp转换为 thunder://
 * Author: zhaolei
 * Date: Since 2018-03-11 00:29:03
 */
@Log4j2
public class Parser {

	private Invocable invocable;

	public Parser() {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		String jsFilePath = classPath("lib/base64.js");
		File jsFile = new File(jsFilePath);
		try {
			String js = Files.toString(jsFile, Charsets.UTF_8);
			engine.eval(js);
		} catch (Exception e) {
			e.printStackTrace();
		}
		invocable = (Invocable) engine;
	}

	public List<String> parse(List<String> rawLinks){
		List<String> retList = rawLinks
				.stream()
				.map(link->thunderEncode(link))
				.collect(toList());
		return retList;
	}

	public String thunderEncode(String url){
		String retThunderLink = null;
		try {
			retThunderLink = (String) invocable.invokeFunction("ThunderEncode",url);
		} catch (ScriptException e) {
			log.error("base64.js加载或执行出错！");
		} catch (NoSuchMethodException e) {
			log.error(e);
		}
		return retThunderLink;
	}
}
